package com.gitee.wsl.transform.validator.strings

import arrow.core.leftNel
import arrow.core.right
import com.gitee.wsl.transform.validator.ValidatorWithTransform
import com.gitee.wsl.transform.validator.func.map
import com.gitee.wsl.transform.validator.transformEither

/**
 * Transforms a String producing [ValidatorWithTransform] into a Boolean producing ValidatorWithError,
 * by converting the String to a Boolean using the library function [toBoolean].
 */
fun <I, E> ValidatorWithTransform<I, String, E>.boolean(): ValidatorWithTransform<I, Boolean, E> =
   transformEither {
      val b = it.toBoolean()
      b.right()
   }

/**
 * Transforms a String producing [ValidatorWithTransform] into a Boolean producing ValidatorWithError,
 * by converting the String to a Boolean using the library function [toBooleanStrict].
 */
fun <I, E> ValidatorWithTransform<I, String, E>.booleanStrict(ifError: (String) -> E): ValidatorWithTransform<I, Boolean, E> =
   transformEither { input ->
      runCatching { input.toBooleanStrict() }.fold({ it.right() }, { ifError(input).leftNel() })
   }

/**
 * Transforms a nullable String producing [ValidatorWithTransform] into a nullable Boolean producing ValidatorWithError,
 * by converting the String to a Boolean using the library function [toBooleanStrictOrNull].
 */
fun <I, E> ValidatorWithTransform<I, String, E>.booleanStrictOrNull(): ValidatorWithTransform<I, Boolean?, E> =
   map { it.toBooleanStrictOrNull() }
